package com.my.content.ui_homework.fragment.HomePage;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.my.content.ui_homework.R;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomePageFragment extends Fragment {


    private ViewPager mVp;
    private TabLayout mTb;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_page, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTb = (TabLayout) view.findViewById(R.id.home_tab);
        mVp = (ViewPager) view.findViewById(R.id.home_vp);
        List<Fragment> fragments = new ArrayList<>();
        String[] title = getResources().getStringArray(R.array.star_title);
        for(int i = 0;i <title.length;i++){
            HomePageItemFragment homePageItemFragment = new HomePageItemFragment();
            fragments.add(homePageItemFragment);
        }
        FragmentAdapter adapter =  new FragmentAdapter(getFragmentManager(), fragments, title);
        mVp.setAdapter(adapter);
//        添加适配器的数据name到mTab中
        mTb.setupWithViewPager(mVp);
        mVp.setCurrentItem(0);
    }

    //viewpager的适配器
    class FragmentAdapter extends FragmentPagerAdapter {
        private List<Fragment> mFragment;
        private String[] mTitle;
        //构造方法，根据需要传入相应的参数
        public FragmentAdapter(FragmentManager fm, List<Fragment> fragments,String[] title) {
            super(fm);
            this.mFragment = fragments;
            this.mTitle = title;
            //刷新界面
            notifyDataSetChanged();
        }

        @Override
        public Fragment getItem(int position) {
            //根据位置得到指定的条目
            return mFragment.get(position);
        }

        @Override
        public int getCount() {
            //ViewPager的数量根据Fragment集合的数量决定
            return mFragment.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            //得到name属性
            return mTitle[position];
        }
    }
}
